<template>
  <div class="reserve-cancel">
    <van-nav-bar
      title="预约发布"
      left-text="返回"
      left-arrow
      fixed
      @click="handleBack"
    />
    <van-cell-group inset class="reserve-top">
      <!-- <van-cell
        :value="userInfo?.tenantName"
        :label="`联系电话：${userInfo?.phone}`"
      >
        <template #title>
          <span class="name">{{ userInfo?.name }}</span>
          <span class="sex">性别:{{ userInfo?.sexName }}</span>
          <span> 年龄:{{ age }} </span>
        </template>
      </van-cell> -->

      <!-- <van-field
        :model-value="reserveDate"
        is-link
        readonly
        label="预约发布日期"
        @click="showReserveDatePicker = true"
      />

      <van-popup v-model:show="showReserveDatePicker" position="bottom">
        <van-datetime-picker
          type="date"
          title="选择年月日"
          @confirm="onConfirm"
          @cancel="showReserveDatePicker = false"
        />
      </van-popup> -->

      <!-- <van-cell center :title="sort">
        <template #right-icon>
          <van-switch
            v-model="sort"
            size="24"
            active-value="正序"
            inactive-value="倒序"
          />
        </template>
      </van-cell> -->
    </van-cell-group>

    <!-- <van-button
      v-show="!isReleased"
      type="primary"
      size="small"
      @click="goToEdit"
    >
      编辑
    </van-button> -->

    <!-- <van-sticky :offset-top="50">
      <div class="form-top">
        <span>预约设置</span>
        <span><van-icon name="add-o" @click="handleAdd" /></span>
      </div>
    </van-sticky> -->

    <ReserveView v-model:form="form">
      <van-button
        type="primary"
        block
        class="reserve-btn"
        @click="handleSubmit"
      >
        {{ btnText }}
      </van-button>
    </ReserveView>
    <!-- <div class="success">
      <van-button
        class="reserve-btn success-btn"
        type="success"
        @click="handleService"
        >完成咨询</van-button
      >
    </div> -->
  </div>
</template>

<script lang="ts" setup>
import { computed, toRefs, ref, defineProps } from 'vue'
import { useStore } from '/@/store'
import dayjs from 'dayjs'
import { useBack } from '/@/use/useRouteBack'
import ReserveView from '../components/ReserveView.vue'
import { useReserveForm } from '../use/useReserveForm'
import { toParams } from '../utils'
import { publishUpdate, publishRemove } from '/@/views/reserve/api'
import { IForm, Status } from '../types'
import { useDatePicker } from '/@/use/datePicker'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'

const props = defineProps({
  id: {
    type: String,
    default: '',
  },
  tenantId: {
    type: String,
    default: '',
  },
})

type PropsType = typeof props

const { state } = useStore()

const { userInfo } = toRefs(state)

const age = computed(
  () => dayjs().year() - dayjs(userInfo.value?.birthday).year()
)

const { back: handleBack } = useBack()

const { sort } = useSearchForm()

const reserveDate = ref('')

const { onConfirm, picker: showReserveDatePicker } = useDatePicker(reserveDate)

const { form } = useReserveForm(toRefs(props).id, toRefs(props).tenantId)

const { isReleased, btnText, handleSubmit, handleService } =
  useReleaseOrCancel(form)

const { goToEdit } = useEdit(form)

function useSearchForm() {
  const sort = ref('正序')
  return { sort }
}

function useEdit(form: IForm) {
  const router = useRouter()
  return {
    goToEdit() {
      router.push({ name: 'ReserveEdit', query: { id: form.id } })
    },
  }
}

function useReleaseOrCancel(form: IForm) {
  const router = useRouter()
  const isReleased = computed(() => form.status === Status.released)
  const handleRelease = async () => {
    const list = [toParams(form)]

    list.map((item) => {
      item.status = Status.released
    })

    const { data } = await publishUpdate(list[0])
    Toast('发布成功')
    router.push({ name: 'ReserveRecord' })
  }

  const handleCancle = async () => {
    const list = [toParams(form)]
    const date = dayjs().format('YYYY-MM-DD').split('-')
    const deadline = form.deadline.split('-')

    const isOverdue = date.every(
      (value, index) => parseInt(value) >= parseInt(deadline[index])
    )
    // if (isOverdue) {
    //   Toast('此预约已过期，无法取消！')
    //   return
    // }

    list.map((item) => {
      item.status = Status.draft
    })

    await publishRemove(list.map(({ id }) => id || '').filter(Boolean))
    Toast('取消成功')
    router.push({ name: 'ReserveRecord' })
  }

  return {
    isReleased,
    btnText: '取消预约',
    // btnText: computed(() => (isReleased.value ? '取消预约' : '发布预约')),
    handleSubmit() {
      // if (isReleased.value) {
      handleCancle()
      // } else {
      //   handleRelease()
      // }
    },
    handleService() {
      console.log(form)
      // if (form?.remainder > 0) {
      //   return Toast('当前预约记录暂时无用户预约！')
      // }
      router.push({
        name: 'ReserveReport',
        query: {
          id: form.id,
          reserveDate: form.reserveDate,
          reserveEndTime: form.reserveEndTime,
          reserveStartTime: form.reserveStartTime,
          status: form.status,
        },
      })
    },
  }
}
</script>

<style lang="less" scoped>
.reserve-cancel {
  padding-top: 60px;
  margin-bottom: 60px;
}

.form-top {
  padding: 20px 20px 12px 20px;
  font-size: 16px;
  font-weight: 700;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f5f7f9;
}

.reserve-top {
  margin-bottom: 30px;
}

.sex,
.name {
  margin-right: 15px;
}

.buttons {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
}

.reserve-btn {
  width: 50%;
  margin: 0 auto;
  margin-top: 20px;
}

.success {
  text-align: center;
  .success-btn {
    margin-top: 0;
  }
}
</style>
